#!/bin/bash
# Entry point for OneTake Installer.app. Same copy logic as install.command,
# adapted for a double-clicked .app bundle: no attached Terminal window, so
# feedback goes through osascript dialogs instead of echo/read.
set -euo pipefail

alert() {
  # $1: message, $2: icon (note|stop). Message is passed as a script
  # argument (not interpolated into AppleScript source) so quotes,
  # newlines, and "&" in it never need escaping. The icon constant can't
  # be passed as a plain string (AppleScript won't coerce it), so branch
  # on it inside the script instead.
  osascript -e 'on run argv' \
            -e 'set msg to item 1 of argv' \
            -e 'if (item 2 of argv) is "stop" then' \
            -e '  display dialog msg buttons {"OK"} default button "OK" with icon stop' \
            -e 'else' \
            -e '  display dialog msg buttons {"OK"} default button "OK" with icon note' \
            -e 'end if' \
            -e 'end run' \
            -- "$1" "$2" >/dev/null
}

APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
SOURCE="$APP_DIR/Contents/Resources/OneTake"
TARGET_DIR="$HOME/Music/Ableton/User Library/Remote Scripts"
TARGET="$TARGET_DIR/OneTake"

if [ ! -d "$SOURCE" ]; then
  alert "エラー: OneTakeフォルダーが見つかりません。アプリが壊れている可能性があります。再ダウンロードをお試しください。" stop
  exit 1
fi

# Sanity check before rm -rf: guard against TARGET ever resolving to
# something unexpected (e.g. a mis-set HOME) wiping the wrong directory.
case "$TARGET" in
  */"Remote Scripts/OneTake") ;;
  *)
    alert "エラー: インストール先が想定外です: $TARGET" stop
    exit 1
    ;;
esac

mkdir -p "$TARGET_DIR"
rm -rf "$TARGET"
cp -R "$SOURCE" "$TARGET"

alert $'OneTakeをインストールしました。\n\n次の手順: Ableton Liveを起動し、Preferences > Link, Tempo & MIDIを開き、Control SurfaceのドロップダウンからOneTakeを選択してください。' note
